package GUI;

import Command.CommandStatement;
import Command.Constant_Command;
import static GUI.MainScreen.lbAccount;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.AbstractButton;
import javax.swing.BorderFactory;
import javax.swing.ButtonModel;
import javax.swing.ImageIcon;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.border.BevelBorder;
import javax.swing.border.TitledBorder;
import remoteserver.ServerInitiator;


public class ComputerPanel extends javax.swing.JPanel {

    /**
     * Creates new form ComputerPanel
     */
    public static final int CLOSE = 0;
    public static final int USE = 1;
    public static final int OPEN = 2;
    private int status;
    private String name;
    private JPopupMenu pmProperties;
    public ObjectInputStream dataIn;
    public ObjectOutputStream dataOut;
    public Socket socket;
    private ReadThread readThread;
    private ServerInitiator TeamViewThread = null;
    private Date startTime;
    public String account;
    public static final String ANONYMOUS = "Anonymous";

    public ComputerPanel() {
    }

    public ComputerPanel(int status, String name, Socket socket) {
        this.name = name;
        initComponents();
        try {
            dataOut = new ObjectOutputStream(socket.getOutputStream());
            dataOut.flush();
            dataIn = new ObjectInputStream(socket.getInputStream());
            this.socket = socket;
            readThread = new ReadThread(dataIn, dataOut);
        } catch (Exception ex) {
            System.out.println("Lo: " + ex.getMessage());
        }
        setStatus(status);
        ppClickRight.setEnabled(false);
        setPreferredSize(new Dimension(100, 105));
        lbName.setText(name);
        pmProperties = new JPopupMenu();
        pmProperties.add(computerProperties);
        btIcon.setContentAreaFilled(false);
        MIDisenabledAll();
    }

    public void setSocket(Socket socket) {
        try {
            dataOut = new ObjectOutputStream(socket.getOutputStream());
            dataOut.flush();
            dataIn = new ObjectInputStream(socket.getInputStream());
            this.socket = socket;
            readThread = new ReadThread(dataIn, dataOut);
            setStatus(OPEN);
        } catch (Exception ex) {
            Logger.getLogger(ComputerPanel.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void MIDisenabledAll() {
        int len = ppClickRight.getComponentCount();
        for (int i = 0; i < len; i++) {
            Component miComponent = ppClickRight.getComponent(i);
            miComponent.setEnabled(false);
        }
    }
    
    public void UpdatePricePerHours(String price){
        try {
            // TODO add your handling code here:
            System.out.println("Sending Update price to computer: " + name);
            dataOut.writeObject(new CommandStatement(Constant_Command.UPDATEPRICEPERHOUR, price));
            dataOut.writeObject(new CommandStatement(Constant_Command.PURE_MESSAGE, "Máy chủ đã thay đổi giá tiền giờ: " + price));
            System.out.println("Sended Update price to computer: " + name);
        } catch (Exception ex) {
            Logger.getLogger(ComputerPanel.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    public void computerClose() {
        status = CLOSE;
        setStatus(status);
        try {
            // TODO add your handling code here:
            dataOut.writeObject(new CommandStatement(Constant_Command.SHUT_DOWN));
            System.out.println("Sended Turn_off sesion to computer: " + name);
            closeConnect();
        } catch (Exception ex) {
        }
    }

    public void closeConnect() {
        try {
            dataIn.close();
            dataOut.close();
            socket.close();
        } catch (IOException ex) {
            Logger.getLogger(ComputerPanel.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        ppClickRight = new javax.swing.JPopupMenu();
        miClose = new javax.swing.JMenuItem();
        miStartSession = new javax.swing.JMenuItem();
        miEndSession = new javax.swing.JMenuItem();
        miRestart = new javax.swing.JMenuItem();
        miDesktop = new javax.swing.JMenuItem();
        miMessage = new javax.swing.JMenuItem();
        computerProperties = new javax.swing.JPanel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        jLabel12 = new javax.swing.JLabel();
        lbStatus = new javax.swing.JLabel();
        lbStartTime = new javax.swing.JLabel();
        lbTimeUsed = new javax.swing.JLabel();
        lbMoney = new javax.swing.JLabel();
        lbIPAddress = new javax.swing.JLabel();
        jLabel20 = new javax.swing.JLabel();
        lbUsername = new javax.swing.JLabel();
        btIcon = new javax.swing.JButton();
        lbName = new javax.swing.JLabel();

        ppClickRight.setEnabled(false);

        miClose.setText("Tắt máy");
        miClose.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.LOWERED, new java.awt.Color(204, 153, 0), new java.awt.Color(255, 51, 0), new java.awt.Color(102, 102, 255), new java.awt.Color(204, 204, 0)));
        miClose.setContentAreaFilled(false);
        miClose.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                miCloseActionPerformed(evt);
            }
        });
        ppClickRight.add(miClose);

        miStartSession.setText(" Mở máy");
        miStartSession.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                miStartSessionActionPerformed(evt);
            }
        });
        ppClickRight.add(miStartSession);

        miEndSession.setText(" Tạm dừng");
        miEndSession.setToolTipText("");
        miEndSession.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                miEndSessionActionPerformed(evt);
            }
        });
        ppClickRight.add(miEndSession);

        miRestart.setText(" Khởi động lại máy");
        miRestart.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                miRestartActionPerformed(evt);
            }
        });
        ppClickRight.add(miRestart);

        miDesktop.setText("Xem màn hình máy con");
        miDesktop.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                miDesktopActionPerformed(evt);
            }
        });
        ppClickRight.add(miDesktop);

        miMessage.setText("Gửi tin nhắn");
        miMessage.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                miMessageActionPerformed(evt);
            }
        });
        ppClickRight.add(miMessage);

        computerProperties.setBackground(new java.awt.Color(226, 201, 249));
        computerProperties.setBorder(BorderFactory.createTitledBorder(BorderFactory.createCompoundBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1), BorderFactory.createBevelBorder(BevelBorder.RAISED, null, null, null, new Color(0, 0, 255))), name, TitledBorder.CENTER, TitledBorder.DEFAULT_POSITION, new Font("Arial", 0, 24), new Color(255, 0, 0)) );

        jLabel5.setBackground(new java.awt.Color(255, 255, 255));
        jLabel5.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
        jLabel5.setForeground(new java.awt.Color(0, 0, 255));
        jLabel5.setText("Thời gian sử dụng:");

        jLabel6.setBackground(new java.awt.Color(255, 255, 255));
        jLabel6.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
        jLabel6.setForeground(new java.awt.Color(0, 0, 255));
        jLabel6.setText("Thời gian bắt đầu:");

        jLabel7.setBackground(new java.awt.Color(255, 255, 255));
        jLabel7.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
        jLabel7.setForeground(new java.awt.Color(0, 0, 255));
        jLabel7.setText("Trạng thái:");

        jLabel9.setBackground(new java.awt.Color(255, 255, 255));
        jLabel9.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
        jLabel9.setForeground(new java.awt.Color(0, 0, 255));
        jLabel9.setText("Tiền internet:");

        jLabel12.setBackground(new java.awt.Color(255, 255, 255));
        jLabel12.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
        jLabel12.setForeground(new java.awt.Color(0, 0, 255));
        jLabel12.setText("Địa chỉ IP:");

        lbStatus.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
        lbStatus.setForeground(new java.awt.Color(255, 0, 0));
        lbStatus.setText("Đang đóng");

        lbStartTime.setBackground(new java.awt.Color(255, 255, 255));
        lbStartTime.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
        lbStartTime.setText("00:00:00.");

        lbTimeUsed.setBackground(new java.awt.Color(255, 255, 255));
        lbTimeUsed.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
        lbTimeUsed.setText("00 giờ, 00 phút.");

        lbMoney.setBackground(new java.awt.Color(255, 255, 255));
        lbMoney.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
        lbMoney.setText("VNĐ.");

        lbIPAddress.setBackground(new java.awt.Color(255, 255, 255));
        lbIPAddress.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
        lbIPAddress.setText("000.000.000.000.");

        jLabel20.setBackground(new java.awt.Color(255, 255, 255));
        jLabel20.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
        jLabel20.setForeground(new java.awt.Color(0, 0, 255));
        jLabel20.setText("Người sử dụng:");

        lbUsername.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
        lbUsername.setForeground(new java.awt.Color(255, 0, 0));
        lbUsername.setText("abc");

        javax.swing.GroupLayout computerPropertiesLayout = new javax.swing.GroupLayout(computerProperties);
        computerProperties.setLayout(computerPropertiesLayout);
        computerPropertiesLayout.setHorizontalGroup(
            computerPropertiesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(computerPropertiesLayout.createSequentialGroup()
                .addGap(10, 10, 10)
                .addGroup(computerPropertiesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(computerPropertiesLayout.createSequentialGroup()
                        .addComponent(jLabel5)
                        .addGap(18, 18, 18)
                        .addComponent(lbTimeUsed))
                    .addGroup(computerPropertiesLayout.createSequentialGroup()
                        .addComponent(jLabel9)
                        .addGap(55, 55, 55)
                        .addComponent(lbMoney))
                    .addGroup(computerPropertiesLayout.createSequentialGroup()
                        .addComponent(jLabel12)
                        .addGap(81, 81, 81)
                        .addComponent(lbIPAddress))
                    .addGroup(computerPropertiesLayout.createSequentialGroup()
                        .addComponent(jLabel7)
                        .addGap(75, 75, 75)
                        .addComponent(lbStatus, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(computerPropertiesLayout.createSequentialGroup()
                        .addGroup(computerPropertiesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel6)
                            .addComponent(jLabel20))
                        .addGap(24, 24, 24)
                        .addGroup(computerPropertiesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lbStartTime)
                            .addComponent(lbUsername, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                .addContainerGap(34, Short.MAX_VALUE))
        );
        computerPropertiesLayout.setVerticalGroup(
            computerPropertiesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(computerPropertiesLayout.createSequentialGroup()
                .addGap(11, 11, 11)
                .addGroup(computerPropertiesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(computerPropertiesLayout.createSequentialGroup()
                        .addGap(4, 4, 4)
                        .addComponent(jLabel7))
                    .addComponent(lbStatus))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(computerPropertiesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(computerPropertiesLayout.createSequentialGroup()
                        .addGap(4, 4, 4)
                        .addComponent(jLabel20))
                    .addComponent(lbUsername))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(computerPropertiesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel6)
                    .addComponent(lbStartTime))
                .addGap(6, 6, 6)
                .addGroup(computerPropertiesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel5)
                    .addComponent(lbTimeUsed))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(computerPropertiesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel9)
                    .addComponent(lbMoney))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(computerPropertiesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel12)
                    .addComponent(lbIPAddress))
                .addContainerGap(142, Short.MAX_VALUE))
        );

        setBackground(null);
        setPreferredSize(new java.awt.Dimension(100, 100));

        btIcon.setBackground(new java.awt.Color(255, 51, 51));
        btIcon.setForeground(new java.awt.Color(255, 255, 255));
        btIcon.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/computerStatus1.png"))); // NOI18N
        btIcon.setBorder(null);
        btIcon.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btIconMouseClicked(evt);
            }
        });
        btIcon.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                btIconStateChanged(evt);
            }
        });
        btIcon.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btIconActionPerformed(evt);
            }
        });
        add(btIcon);

        lbName.setBackground(new java.awt.Color(255, 255, 255));
        lbName.setFont(new java.awt.Font("Arial", 1, 18)); // NOI18N
        lbName.setText("Máy");
        add(lbName);
    }// </editor-fold>//GEN-END:initComponents

    private void btIconActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btIconActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_btIconActionPerformed

    private void btIconStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_btIconStateChanged
        // TODO add your handling code here:
        AbstractButton aButton = (AbstractButton) evt.getSource();
        ButtonModel aModel = aButton.getModel();
        if (aModel.isRollover()) {
            Point location = btIcon.getLocation(), locationScreen = btIcon.getLocationOnScreen();
            pmProperties.setVisible(true);
            Toolkit toolkit = Toolkit.getDefaultToolkit();
            Dimension screenSize = toolkit.getScreenSize();
            int X = (int) locationScreen.getX() + 55, Y = (int) locationScreen.getY();
            if (X + pmProperties.getSize().getWidth() > screenSize.width) {
                X = (int) (location.getX() - pmProperties.getSize().getWidth() - 15);
            } else {
                X = (int) location.getX() + 55;
            }
            if (Y + computerProperties.getHeight() > screenSize.height) {
                Y = (int) (location.getY() - pmProperties.getSize().getHeight() + 45);
            } else {
                Y = (int) location.getY();
            }
            RedisplayStatusPanel();
            pmProperties.show(btIcon, X, Y);
        }
        pmProperties.setVisible(aModel.isRollover());
        btIcon.setContentAreaFilled(aModel.isRollover());
    }//GEN-LAST:event_btIconStateChanged

    private void btIconMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btIconMouseClicked
        // TODO add your handling code here:
        if (evt.getButton() == MouseEvent.BUTTON3) {
            ppClickRight.show(this, (int) getMousePosition().getLocation().getX(),
                    (int) getMousePosition().getLocation().getY());
        }
    }//GEN-LAST:event_btIconMouseClicked

    private void miCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_miCloseActionPerformed
        computerClose();
    }//GEN-LAST:event_miCloseActionPerformed

    private void miStartSessionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_miStartSessionActionPerformed
        try {
            System.out.println("Sending Turn_on to computer: " + name);
            dataOut.writeObject(new CommandStatement(Constant_Command.TURN_ON_SERVICE, "Anonymous", "-1"));
            this.startTime = Calendar.getInstance().getTime();
            System.out.println("Sended Turn_on to computer: " + name);
            status = USE;
            setStatus(status);
        } catch (Exception ex) {
            Logger.getLogger(ComputerPanel.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_miStartSessionActionPerformed

    private void miEndSessionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_miEndSessionActionPerformed
        // TODO add your handling code here:        
        try {
            // TODO add your handling code here:
            dataOut.writeObject(new CommandStatement(Constant_Command.TURN_OFF_SERVICE));
            System.out.println("Sended Turn_off to computer: " + name);
            //dataOut.writeObject(new CommandStatement(Constant_Command));
            status = OPEN;
            startTime = null;
            setStatus(status);
        } catch (Exception ex) {
            Logger.getLogger(ComputerPanel.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_miEndSessionActionPerformed

    private void miRestartActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_miRestartActionPerformed
        // TODO add your handling code here:
        MIDisenabledAll();
        try {
            // TODO add your handling code here:
            dataOut.writeObject(new CommandStatement(Constant_Command.RESTART));
            status = CLOSE;
            setStatus(status);
        } catch (Exception ex) {
            Logger.getLogger(ComputerPanel.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_miRestartActionPerformed

    private void miDesktopActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_miDesktopActionPerformed
        // TODO add your handling code here:
        try {
            // TODO add your handling code here:
            dataOut.writeObject(new CommandStatement(Constant_Command.TEAMVIEW));
        } catch (Exception ex) {
            Logger.getLogger(ComputerPanel.class.getName()).log(Level.SEVERE, null, ex);
        }
        if (TeamViewThread != null && TeamViewThread.isAlive()) {
            TeamViewThread.interrupt();
            TeamViewThread.suspend();
        }
        TeamViewThread = new ServerInitiator();
    }//GEN-LAST:event_miDesktopActionPerformed

    private void miMessageActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_miMessageActionPerformed
        // TODO add your handling code here:
        String content = JOptionPane.showInputDialog(null);
        if (content != null) {
            sendMessage(content);
        }
    }//GEN-LAST:event_miMessageActionPerformed
    public void sendMessage(String content) {
        try {
            dataOut.writeObject(new CommandStatement(Constant_Command.PURE_MESSAGE, content));
        } catch (IOException ex) {
            Logger.getLogger(ComputerPanel.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void setIcon(int status) {
        btIcon.setIcon(new ImageIcon(getClass().getResource("/images/computerStatus" + status + ".png")));
    }

    public int getStatus() {
        return status;
    }

    public void setStatus(int status) {
        this.status = status;
        if (status == OPEN) {
            miEndSession.setEnabled(false);
            miDesktop.setEnabled(false);
            miStartSession.setEnabled(true);
            miClose.setEnabled(true);
            miRestart.setEnabled(true);
            miMessage.setEnabled(false);
            lbStatus.setText("Tạm dừng");
        } else if (status == USE) {
            miEndSession.setEnabled(true);
            miDesktop.setEnabled(true);
            miStartSession.setEnabled(false);
            miClose.setEnabled(true);
            miRestart.setEnabled(true);
            miMessage.setEnabled(true);
            lbStatus.setText("Đang sử dụng");
        } else {
            lbStatus.setText("Mất kết nối");
            MIDisenabledAll();
        }
        setIcon(status);
    }

    public String getName() {
        return name;
    }

    public String getEmployeeID() {
        try {
            String query = "SELECT EMPLOYEEID FROM EMPLOYEE WHERE EMPLOYEENAME='" + lbAccount.getText() + "'";
            String id = "";
            ResultSet rs = Login.dtConnect.retriveData(query);
            if (rs.next()) {
                id = rs.getString(1);
            }
            return id;
        } catch (SQLException ex) {
            Logger.getLogger(ComputerPanel.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
    }

    public void RedisplayStatusPanel() {
        if (status == USE) {
            lbUsername.setText(account);
            lbIPAddress.setText(socket.getInetAddress().toString());
            String start = new SimpleDateFormat("HH:mm:ss dd-MM-yyyy").format(startTime.getTime());
            lbStartTime.setText(start);

            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date d1 = startTime;
            Date d2 = Calendar.getInstance().getTime();
            Date diff = new Date(d2.getTime() - d1.getTime());
            Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
            calendar.setTime(diff);
            int hours = calendar.get(Calendar.HOUR_OF_DAY);
            int minutes = calendar.get(Calendar.MINUTE);
            int seconds = calendar.get(Calendar.SECOND);
            lbTimeUsed.setText(hours + " giờ, " + minutes + " phút, " + seconds + " giây.");

            int total = minutes + hours * 60;
            int cost = (int) ((float) total / 60 * Login.pricePerHour);
            cost = cost / 100;
            cost = cost * 100;
            lbMoney.setText(String.valueOf(cost) + " VND");
        } else {
            lbUsername.setText("Không xác định.");
            lbStartTime.setText("00:00:00.");
            lbTimeUsed.setText("00 giờ, 00 phút.");
            lbMoney.setText("0 VND");
        }

    }

    public void setName(String name) {
        this.name = name;
        lbName.setText(name);
    }

    public void updateTransaction(String timeStart, String mins) {
        int min = Integer.valueOf(mins);
        int cost = (int) ((float) min / 60 * Login.pricePerHour);
        cost = cost / 100;
        cost = cost * 100;
        String end = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime());

        String query = "INSERT INTO TRANSACTIONS (NAMECOM,EMPLOYEEID,USERNAME,TIMESTART,TIMEEND,COST)"
                + " VALUES ('" + name + "', '" + getEmployeeID() + "', '" + ANONYMOUS + "','" + timeStart + "','"
                + end + "','" + String.valueOf(cost) + "')";
        Login.dtConnect.updateData(query);
            int month=0;
            month=Calendar.getInstance().get(Calendar.MONTH)+1;
            MainScreen.dataMana.updateStatistic(Calendar.getInstance().get(Calendar.DATE),month , Calendar.getInstance().get(Calendar.YEAR), cost);
    }
    
    public boolean ConfirmDialog(String title, String message){
        int result = JOptionPane.showConfirmDialog(null, message, title, JOptionPane.YES_NO_OPTION);
        if (result == JOptionPane.OK_OPTION){
            return true;
        }
        else{
            return false;
        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btIcon;
    private javax.swing.JPanel computerProperties;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel20;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JLabel lbIPAddress;
    private javax.swing.JLabel lbMoney;
    private javax.swing.JLabel lbName;
    private javax.swing.JLabel lbStartTime;
    private javax.swing.JLabel lbStatus;
    private javax.swing.JLabel lbTimeUsed;
    private javax.swing.JLabel lbUsername;
    private javax.swing.JMenuItem miClose;
    private javax.swing.JMenuItem miDesktop;
    private javax.swing.JMenuItem miEndSession;
    private javax.swing.JMenuItem miMessage;
    private javax.swing.JMenuItem miRestart;
    private javax.swing.JMenuItem miStartSession;
    private javax.swing.JPopupMenu ppClickRight;
    // End of variables declaration//GEN-END:variables

    public class ReadThread extends Thread {

        private ObjectInputStream ois = null;
        private ObjectOutputStream oos = null;
        public boolean IsWorking = false;

        public ReadThread(ObjectInputStream _ObjectInputStream, ObjectOutputStream _ObjectOutputStream) {
            this.ois = _ObjectInputStream;
            this.oos = _ObjectOutputStream;
            //this.startTime = Calendar.getInstance().getTime();
            account = ANONYMOUS;
            start();
        }

        public void LoginTest(String _account, String _password) {
            try {
                String query = "SELECT * FROM USER";
                ResultSet resultSet = Login.dtConnect.retriveData(query);
                boolean login = false;
                int mins = -1;
                while (resultSet.next()) {
                    if (resultSet.getString(1).equals(_account) && resultSet.getString(2).equals(_password)) {
                        login = true;
                        account = resultSet.getString(1);
                        mins = resultSet.getInt(4);
                        break;
                    } else {
                        account = ANONYMOUS;
                    }
                }
                if (login) {
                    startTime = Calendar.getInstance().getTime();
                    oos.writeObject(new CommandStatement(Constant_Command.TURN_ON_SERVICE, account, String.valueOf(mins)));
                    setStatus(USE);
                } else {
                    oos.writeObject(new CommandStatement(Constant_Command.PURE_MESSAGE, "Log-in failed!"));
                }
            } catch (Exception ex) {
                Logger.getLogger(ComputerPanel.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        public void updateAccountMins(String mins) {
            String query = "UPDATE user SET MINSREMAIN='" + mins + "' WHERE USERNAME='" + account + "'";
            Login.dtConnect.updateData(query);
        }

        public void ChangePass(String oldPass, String newPass) {
            try {
                String query1 = "SELECT PASSWORD FROM USER WHERE USERNAME='" + account + "'";
                System.out.println(account);
                ResultSet resultSet = Login.dtConnect.retriveData(query1);
                String old = "";
                if (resultSet.next()) {
                    old = resultSet.getString(1);
                    System.out.println(old);
                    if (old.equals(oldPass)) {
                        String query = "UPDATE user SET PASSWORD='" + newPass + "' WHERE USERNAME='" + account + "'";
                        Login.dtConnect.updateData(query);
                        oos.writeObject(new CommandStatement(Constant_Command.PURE_MESSAGE, "Đổi mật khẩu thành công!"));
                        System.out.println("Thanh cong");
                    } else {
                        oos.writeObject(new CommandStatement(Constant_Command.PURE_MESSAGE, "Đổi mật khẩu thất bại!"));
                        System.out.println("That bai");
                    }
                }
            } catch (SQLException ex) {
                Logger.getLogger(ComputerPanel.class.getName()).log(Level.SEVERE, null, ex);
            } catch (Exception ex) {
                Logger.getLogger(ComputerPanel.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        public void ReCharge(String m) {
            if (!ConfirmDialog("Thông báo", name + " yêu cầu nạp số tiền " + m + ". Chấp nhận yêu cầu này?")){
                try {
                    dataOut.writeObject(new CommandStatement(Constant_Command.PURE_MESSAGE, "Quản trị viên không chấp nhận yêu cầu nạp tiền của bạn!"));
                } catch (IOException ex) {
                    Logger.getLogger(ComputerPanel.class.getName()).log(Level.SEVERE, null, ex);
                }
                return;
            }
            try {
                String query = "SELECT MINSREMAIN FROM USER WHERE USERNAME='" + account + "'";
                ResultSet rs = Login.dtConnect.retriveData(query);
                rs.next();
                int curMin = rs.getInt(1);
                int money = Integer.valueOf(m);
                int min2Add = (int) (60 * ((float) money / Login.pricePerHour));
                curMin += min2Add;

                String currentTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime());
                query = "UPDATE USER SET MINSREMAIN='" + curMin + "', LASTTRANSACTION='"
                        + currentTime + "', LASTDEPOSIT='" + money + "' WHERE USERNAME='" + account + "'";
                Login.dtConnect.updateData(query);

                query = "SELECT EMPLOYEEID FROM EMPLOYEE WHERE EMPLOYEENAME='" + lbAccount.getText() + "'";
                rs = Login.dtConnect.retriveData(query);
                rs.next();
                String employeeID = rs.getString(1);

                query = "INSERT INTO TRANSACTIONS (COST,EMPLOYEEID,USERNAME,TIMESTART) VALUES ('"
                        + money + "', '" + employeeID + "', '" + account + "', '" + currentTime + "')";
                Login.dtConnect.updateData(query);
                int month = 0;
                month = Calendar.getInstance().get(Calendar.MONTH) + 1;
                MainScreen.dataMana.updateStatistic(Calendar.getInstance().get(Calendar.DATE), month, Calendar.getInstance().get(Calendar.YEAR), money);
                //Return message
                dataOut.writeObject(new CommandStatement(Constant_Command.PURE_MESSAGE, "Yêu cầu nạp tiền của bạn thành công!"));
                dataOut.writeObject(new CommandStatement(Constant_Command.UPDATEMINREMAIN, String.valueOf(curMin)));
            } catch (SQLException ex) {
                try {
                    dataOut.writeObject(new CommandStatement(Constant_Command.PURE_MESSAGE, "Yêu cầu nạp tiền của bạn xảy ra lỗi! Thử lại sau!"));
                    Logger.getLogger(ComputerPanel.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IOException ex1) {
                    Logger.getLogger(ComputerPanel.class.getName()).log(Level.SEVERE, null, ex1);
                }
            } catch (IOException ex) {
                Logger.getLogger(ComputerPanel.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        @Override
        public void run() {
            IsWorking = true;
            while (IsWorking) {
                try {
                    CommandStatement comm = (CommandStatement) ois.readObject();
                    System.out.println(name + " sent mess: " + comm.getId() + comm.getSt1() + comm.getSt2());
                    switch (comm.getId()) {
//                        case Constant_Command.TURN_ON_SERVICE:
//                            setStatus(OPEN);
//                            
//                            break;
                        case Constant_Command.TURN_OFF_SERVICE:
                            setStatus(OPEN);
                            if (account.equals(ANONYMOUS)) {
                                updateTransaction(comm.getSt1(), comm.getSt2());
                            } else {
                                updateAccountMins(comm.getSt1());
                            }

                            break;
                        case Constant_Command.LOGIN:
                            String username = comm.getSt1();
                            String password = comm.getSt2();
                            LoginTest(username, password);
                            break;
                        case Constant_Command.CHANGE_PASSWORD:
                            ChangePass(comm.getSt1(), comm.getSt2());
                            break;
                        case Constant_Command.CARD_REQUEST:
                            
                            ReCharge(comm.getSt1());
                            break;
                        case Constant_Command.TEAMVIEW:
                            if (TeamViewThread != null && TeamViewThread.IsWorking) {
                                TeamViewThread.imageIcon = comm.getImage();
                            } else {
                                oos.writeObject(new CommandStatement(Constant_Command.TURNOFF_TEAMVIEW));
                            }
                            break;
                    }
                    Thread.sleep(500);
                } catch (Exception ex) {
                    JOptionPane.showConfirmDialog(null, name + " đã ngắt kết nối!", "Máy con ngắt kết nối", JOptionPane.WARNING_MESSAGE);
                    setStatus(CLOSE);
                    IsWorking = false;
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date d1 = startTime;
                    Date d2 = Calendar.getInstance().getTime();
                    Date diff = new Date(d2.getTime() - d1.getTime());
                    Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
                    calendar.setTime(diff);

                    int hours = calendar.get(Calendar.HOUR_OF_DAY);
                    int minutes = hours * 60 + calendar.get(Calendar.MINUTE);

                    calendar.setTime(d1);
                    if (account.equals(ANONYMOUS)) {
                        updateTransaction(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calendar.getTime()), String.valueOf(minutes));
                    } else {
                        updateAccountMins(String.valueOf(minutes));
                    }
                    Logger.getLogger(ComputerPanel.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
}
